const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
var app = getApp();
const day12 =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var innerAudioContext=null;
function buttonClicked(self) {  //防止重复点击
  self.setData({
    buttonClicked: true
  })
  setTimeout(function () {
    self.setData({
      buttonClicked: false
    })
  }, 500)
}
function showBuyModal(self,fu) {
  // 显示遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "ease",
    delay: 0
  });
  self.animation = animation
  if(fu==-1 || fu==1){
    animation.translateY(600*fu).step();
    self.setData({
      animationData2: animation.export() // export 方法每次调用后会清掉之前的动画操作。
    })
    setTimeout(() => {
      animation.translateY(0).step()
      self.setData({
        animationData2: animation.export()  // export 方法每次调用后会清掉之前的动画操作。
      })
    }, 50)
  }else{
    animation.translateY(600).step();
    self.setData({
      animationData: animation.export() // export 方法每次调用后会清掉之前的动画操作。
    })
    setTimeout(() => {
      animation.translateY(0).step()
      self.setData({
        animationData: animation.export()  // export 方法每次调用后会清掉之前的动画操作。
      })
    }, 50)
  }  
}

function hideBuyModal(self,a,fu) {
  // 隐藏遮罩层
  var animation = wx.createAnimation({
    duration: 200,
    timingFunction: "ease",
    delay: 0
  })
  self.animation = animation
  if(a=="is_screen"){
    animation.translateY(-600).step();
    self.setData({
      animationData2: animation.export()
    });
  }else{
    animation.translateY(600).step();
    if(fu==2){
      self.setData({
        animationData2: animation.export()
      });
    }else{
      self.setData({
        animationData: animation.export()
      });
    };
  };
  if(a=="is_screen"){ //筛选下拉
    setTimeout(function () {
      animation.translateY(0).step()
      self.setData({
        animationData2: animation.export(),
        is_screen: false
      })
    }.bind(self), 200)
  }else{
    setTimeout(function () {
      animation.translateY(0).step()
      self.setData({
        animationData: animation.export(),
        [a]: false
      });
    }.bind(self), 200)
  };
};
function keyfunction(e,self,keep){
  var keys = e.currentTarget.dataset.keys,
      content = self.data.content,
      len = content.length;
      if(wx.getStorageSync('audio')){
        innerAudioContext=null;
        innerAudioContext = wx.createInnerAudioContext();
        innerAudioContext.autoplay = true;//音频自动播放设置   
      };   
    switch (keys) {
      case '·': //点击小数点，（注意输入字符串里的是小数点，但是我界面显示的点不是小数点，是居中的点，在中文输入法下按键盘最左边从上往下数的第二个键，也就是数字键1左边的键可以打出居中的点）
        if (len < 11 && content.indexOf('.') == -1) { //如果字符串里有小数点了，则不能继续输入小数点，且控制最多可输入10个字符串
          if (content.length < 1) { //如果小数点是第一个输入，那么在字符串前面补上一个0，让其变成0.
            content = '0.';
          } else { //如果不是第一个输入小数点，那么直接在字符串里加上小数点
            content += '.';
          }
        };
        if(wx.getStorageSync('audio')){
          innerAudioContext.src = "/mp3/dian.wav";   
        };       
        break;
      case '<': //如果点击删除键就删除字符串里的最后一个
        content = content.substr(0, content.length - 1);
        break;
      default:
        let Index = content.indexOf('.'); //小数点在字符串中的位置
        if (Index == -1 || len - Index != keep) { //这里控制小数点只(keep-1)位
          if (len < 11) { //控制最多可输入10个字符串
            content += keys;
          }
        };  
        if(wx.getStorageSync('audio')){
          innerAudioContext.src = "/mp3/"+keys+".wav";
        };     
        break
    };
    if(wx.getStorageSync('audio')){
      innerAudioContext.onPlay(() => { 
        console.log("playing");   
      }); 
    };   
  self.setData({
    content
  });
}
function car_total(self,id,is_ku){
  app.AppHttp('api/Shopping/getShoppingSmInfo', {
    openid: app.globalData.openid,
    supplier_id:id,
    submit_type: 1, //正式单
    is_ku:is_ku
  }, function (res) {
    // console.log(JSON.stringify(res.data));
    if (res.data.status == -1) {
      self.setData({
        total: 0
      });
      return;
    };
    self.setData({
      total: res.data.count
    });
  })
}
function touchOnGoods(seft,a,id,type,is_ku){
  // 如果good_box正在运动
  if (!seft.data.hide_good_box) return;
  seft.finger = {};
  var topPoint = {};
  seft.finger['x'] = a.clientX;
  seft.finger['y'] = a.clientY;
  if (seft.finger['y'] < seft.busPos['y']) {
    topPoint['y'] = seft.finger['y'] - 150;
  } else {
    topPoint['y'] = seft.busPos['y'] - 150;
  }
  // 向右抛物线
  // topPoint['x'] = Math.abs(seft.finger['x'] - seft.busPos['x']) / 2 + seft.finger['x'];
  // 向左抛物线
  topPoint['x'] = seft.finger['x'] - Math.abs(seft.finger['x'] - seft.busPos['x']) / 2;
  // seft.finger, topPoint, seft.busPos分别为点击位置坐标，抛物线最高点坐标，购物车位置坐标
  seft.linePos = app.bezier([seft.finger, topPoint, seft.busPos], 20);
  startAnimation(seft,id,type,is_ku);
}

function startAnimation(seft,id,type,is_ku){
  var index = 0,
    bezier_points = seft.linePos['bezier_points'];
  seft.setData({
    hide_good_box: false,
    bus_x: seft.finger['x'],
    bus_y: seft.finger['y']
  })
  seft.timer = setInterval(function () {
    index++;
    seft.setData({
      bus_x: bezier_points[index]['x'],
      bus_y: bezier_points[index]['y']
    })
    if (index >= 18) {
      clearInterval(seft.timer);
      if(type=='nopand'){
        car_total(seft,id,is_ku);
      }   
      seft.setData({
        hide_good_box: true
      });
    }
  }, 33);
}
// 年、月、日改变
function bindchange_time(e,seft,date){
  const val = e.detail.value
    seft.setData({
      year: seft.data.years[val[0]],
      month: seft.data.months[val[1]],
      day: seft.data.days[val[2]],
      value: [seft.data.years[val[0]] - 2010, seft.data.months[val[1]] - 1, seft.data.days[val[2]] - 1]
    });
    if((seft.data.years[val[0]] % 4 === 0 && seft.data.years[val[0]]%100!== 0) ||seft.data.years[val[0]] % 400 === 0){
      day12[1]=29;
    }else{
      day12[1]=28;
    };
    if(seft.data.years[val[0]]<date.getFullYear()){
      seft.setData({
        months:[1,2,3,4,5,6,7,8,9,10,11,12]
      });
    }else{
      seft.setData({
        months:seft.data.months.splice(0,date.getMonth()+1)
      });
    };
    if(seft.data.months[val[1]]<date.getMonth()+1 || seft.data.years[val[0]]<date.getFullYear()){
      var days=[];
      for (let i = 1; i <= day12[seft.data.months[val[1]]-1]; i++) {
        days.push(i);
      }
      seft.setData({
        days:days
      });
    }else if(seft.data.months[val[1]]>=date.getMonth()+1 && seft.data.years[val[0]]==date.getFullYear()){
      var days=[];
      for (let i = 1; i<date.getDate()+1; i++) {
        days.push(i);
      }
      seft.setData({
        days:days
      });
    };
    var str = seft.data.year + '-' + seft.data.month + '-' + seft.data.day
    if (seft.data.time_type == 0) {
      seft.setData({
        z_start_time: str
      })
    } else if (seft.data.time_type == 1) {
      seft.setData({
        z_end_time: str
      })
    }
}
// 重新登录（用于由于网络or服务器原因导致管理员变成员工）
function again_login(){
  wx.showModal({
    title: '提示',
    content: "请重新登录系统",
    showCancel: false,
    confirmText:"重新登录",
    success: function (res) {
      app.AppHttp('api/Supplier/updateManageField', {
        person_id:app.globalData.person_id,
        type:'client',
        is_manage:'2'
      }, function (res) {
        console.log(JSON.stringify(res.data));
        wx.reLaunch({
          url: "/pages/shangpin/shangpin"
        })
      })
    }
  });
}
function due_Date(diffValue){ //传入到期时间，得到到期剩余天数
  var nowTime = (new Date()).getTime(); // 获取当前时间戳
  var minute = 60;
  var hour = minute * 60;
  var day = hour * 24 *1000;				
  var dayC =(diffValue*1000-nowTime)/day;
  var res = '';
  res = Math.ceil(dayC); //剩余天数进一法
  return res;  
};
// 审批消息
function check_news(seft){
  console.log("审批消息");
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
module.exports = {
  formatTime: formatTime,
  buttonClicked: buttonClicked,
  showBuyModal:showBuyModal,
  hideBuyModal:hideBuyModal,
  keyfunction:keyfunction,
  car_total:car_total,
  touchOnGoods:touchOnGoods,
  startAnimation:startAnimation,
  bindchange_time:bindchange_time,
  check_news:check_news,
  again_login:again_login,
  due_Date:due_Date
}
